package com.ruoyi.jihuo.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.jihuo.domain.JhTmGoods;
import com.ruoyi.jihuo.mapper.JhTmGoodsMapper;
import com.ruoyi.jihuo.service.IJhTmGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class IJhTmGoodsServiceImpl extends ServiceImpl<JhTmGoodsMapper, JhTmGoods> implements IJhTmGoodsService {

    @Autowired
    private JhTmGoodsMapper jhTmGoodsMapper;

    @Override
    public JhTmGoods selectJhTmGoodsByJhId(String jhId) {
        return null;
    }

    @Override
    public JhTmGoods insertJhTmGoods(JhTmGoods jhTmGoods) {
        int i = jhTmGoodsMapper.insert(jhTmGoods);
        return jhTmGoods;
    }

    @Override
    public int insertJhTmGoodsByJson(String itemJson, Long jhTmUploadDataId) {
        JhTmGoods jhTmGoods = new JhTmGoods();
        jhTmGoods.setJhUploadDataId(jhTmUploadDataId);

        JSONObject jsonObject = JSONObject.parseObject(itemJson);
        JSONObject content = jsonObject.getJSONObject("content");
        String brand = content.getString("brand");
        jhTmGoods.setJhBrand(brand);

        JSONObject catProp = content.getJSONObject("catProp");
        Map<String, String> catPropMap = new HashMap<>();
        catProp.forEach((k, v) -> {
            catPropMap.put(k, v.toString());
        });
        jhTmGoods.setJhCatProp(catPropMap);

        String categoryId = content.getString("categoryId");
        jhTmGoods.setJhCategoryId(categoryId);

        // 图片需要替换
        String cover = content.getString("cover");
        jhTmGoods.setJhCover(cover);

        // 描述里面的图需要替换
        String desc = content.getString("desc");
        jhTmGoods.setJhDesc(desc);

        // 展示价格是所有sku的最低值 没用了
        Long disPrice = content.getLong("disPrice");
        jhTmGoods.setJhDisprice(disPrice);

        // 商品展示图，5张
        JSONArray images = content.getJSONArray("images");
        List<String> imageList = new ArrayList<>();
        for (int i = 0; i < images.size(); i++) {
            String image = images.getString(i);
            imageList.add(image);
        }
        jhTmGoods.setJhImages(imageList);

        String itemId = content.getString("itemId");
        jhTmGoods.setJhItemId(itemId);

        // 源商品发货地 没用了
        String location = content.getString("location");
        jhTmGoods.setJhLocation(location);

        // 原价 没用了
        String origPrice = content.getString("origPrice");
        jhTmGoods.setJhOrigprice(origPrice);

        // 促销价 没用了
        String promoPrice = content.getString("promoPrice");
        jhTmGoods.setJhPromoprice(promoPrice);

        // 库存 不一定准
        Long quantity = content.getLong("quantity");
        jhTmGoods.setJhQuantity(quantity);

        // 已知 有颜色分类信息
        JSONArray saleProps = content.getJSONArray("saleProps");
        jhTmGoods.setJhSaleProps(saleProps);

        // 销量 没啥用
        Integer sell = content.getInteger("sell");
        jhTmGoods.setJhSell(sell);

        String shopId = content.getString("shopId");
        jhTmGoods.setJhShopId(shopId);

        String shopName = content.getString("shopName");
        jhTmGoods.setJhShopName(shopName);

        JSONArray skus = content.getJSONArray("skus");
        jhTmGoods.setJhSkus(skus);

        String title = content.getString("title");
        jhTmGoods.setJhTitle(title);

        String video = content.getString("video");
        jhTmGoods.setJhVideo(video);

        int result = jhTmGoodsMapper.insert(jhTmGoods);
        return result;
    }

    @Override
    public List<JhTmGoods> selectJhTmGoodsListByPackageId(Long jhTmUploadDataId) {
        List<JhTmGoods> jhTmGoods = jhTmGoodsMapper.selectJhTmGoodsListByPackageId(jhTmUploadDataId);
        return jhTmGoods;
    }

    @Override
    public boolean existsInRecentMonths(String numIid, int months) {
        Integer count = this.lambdaQuery()
                .eq(JhTmGoods::getJhItemId, numIid)
                .ge(JhTmGoods::getJhCreatedTime, LocalDateTime.now().minusMonths(months))
                .count();
        return count != null && count > 0;
    }

    @Override
    public JhTmGoods convertJsonToGoods(String itemJson, Long jhId) {

        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(itemJson);

            if (rootNode.has("content")) {
                //接口一
                return this.convertJsonToGoodsOne(itemJson, jhId);
            } else {
                //接口二
                return this.convertJsonToGoodsTwo(itemJson, jhId);
            }
        } catch (Exception e) {
            throw new RuntimeException("解析 JSON 失败", e);
        }
    }

    @Override
    public List<JhTmGoods> selectJhTmGoodsByJhItemIdOrderByDesc(String itemId) {
        return jhTmGoodsMapper.selectJhTmGoodsByJhItemIdOrderByDesc(itemId);
    }

    private JhTmGoods convertJsonToGoodsOne(String itemJson, Long jhId){
        JhTmGoods jhTmGoods = new JhTmGoods();
        jhTmGoods.setJhUploadDataId(jhId);

        JSONObject jsonObject = JSONObject.parseObject(itemJson);
        JSONObject content = jsonObject.getJSONObject("content");
        String brand = content.getString("brand");
        jhTmGoods.setJhBrand(brand);

        JSONObject catProp = content.getJSONObject("catProp");
        Map<String, String> catPropMap = new HashMap<>();
        catProp.forEach((k, v) -> {
            catPropMap.put(k, v.toString());
        });
        jhTmGoods.setJhCatProp(catPropMap);

        String categoryId = content.getString("categoryId");
        jhTmGoods.setJhCategoryId(categoryId);

        // 图片需要替换
        String cover = content.getString("cover");
        jhTmGoods.setJhCover(cover);

        // 描述里面的图需要替换
        String desc = content.getString("desc");
        jhTmGoods.setJhDesc(desc);

        // 展示价格是所有sku的最低值 没用了
        Long disPrice = content.getLong("disPrice");
        jhTmGoods.setJhDisprice(disPrice);

        // 商品展示图，5张
        JSONArray images = content.getJSONArray("images");
        List<String> imageList = new ArrayList<>();
        for (int i = 0; i < images.size(); i++) {
            String image = images.getString(i);
            imageList.add(image);
        }
        jhTmGoods.setJhImages(imageList);

        String itemId = content.getString("itemId");
        jhTmGoods.setJhItemId(itemId);

        // 源商品发货地 没用了
        String location = content.getString("location");
        jhTmGoods.setJhLocation(location);

        // 原价 没用了
        String origPrice = content.getString("origPrice");
        jhTmGoods.setJhOrigprice(origPrice);

        // 促销价 没用了
        String promoPrice = content.getString("promoPrice");
        jhTmGoods.setJhPromoprice(promoPrice);

        // 库存 不一定准
        Long quantity = content.getLong("quantity");
        jhTmGoods.setJhQuantity(quantity);

        // 已知 有颜色分类信息
        JSONArray saleProps = content.getJSONArray("saleProps");
        jhTmGoods.setJhSaleProps(saleProps);

        // 销量 没啥用
//        Integer sell = content.getInteger("sell");
//        jhTmGoods.setJhSell(sell);

        String shopId = content.getString("shopId");
        jhTmGoods.setJhShopId(shopId);

        String shopName = content.getString("shopName");
        jhTmGoods.setJhShopName(shopName);

        JSONArray skus = content.getJSONArray("skus");
        jhTmGoods.setJhSkus(skus);

        String title = content.getString("title");
        if (title.length() > 30) {
            title = title.substring(0, 30);
        }
        jhTmGoods.setJhTitle(title);

        String video = content.getString("video");
        jhTmGoods.setJhVideo(video);
        return jhTmGoods;
    }

    private JhTmGoods convertJsonToGoodsTwo(String itemJson, Long jhId){
        this.checkCodeOrThrow(itemJson);

        JhTmGoods jhTmGoods = new JhTmGoods();
        jhTmGoods.setJhUploadDataId(jhId);

        JSONObject content = JSONObject.parseObject(itemJson);
        JSONArray properties = content.getJSONArray("properties");
        if (properties !=null){
            Map<String, String> propsMap = properties.stream()
                    .collect(Collectors.toMap(
                            prop -> ((JSONObject) prop).getString("key"),
                            prop -> ((JSONObject) prop).getString("value")
                    ));
            String brand = propsMap.get("品牌");
            jhTmGoods.setJhBrand(brand);

            jhTmGoods.setJhCatProp(propsMap);
        }


        String categoryId = content.getString("categoryId");
        jhTmGoods.setJhCategoryId(categoryId);

        // 图片需要替换
        String cover = content.getString("coverUrl");
        jhTmGoods.setJhCover(cover);

        // 描述里面的图需要替换
        String desc = content.getString("pcDescUrl");
        jhTmGoods.setJhDesc(desc);

        // 展示价格是所有sku的最低值 没用了
        JSONArray skus = content.getJSONArray("skus");
        long minPrice = Long.MAX_VALUE;

        for (int i = 0; i < skus.size(); i++) {
            JSONObject sku = skus.getJSONObject(i);
            long price = sku.getLongValue("price");
            if (price < minPrice) {
                minPrice = price;
            }
        }
        jhTmGoods.setJhDisprice(minPrice);

        // 商品展示图，5张
        JSONArray images = content.getJSONArray("mainImages");
        List<String> imageList = new ArrayList<>();
        for (int i = 0; i < images.size(); i++) {
            String image = images.getString(i);
            imageList.add(image);
        }
        jhTmGoods.setJhImages(imageList);

        String itemId = content.getString("goodsId");
        jhTmGoods.setJhItemId(itemId);

        // 源商品发货地 没用了
        String location = content.getString("location");
        jhTmGoods.setJhLocation(location);

        // 原价 没用了
        String origPrice = content.getString("originPrice");
        jhTmGoods.setJhOrigprice(origPrice);

        // 促销价 没用了
        String promoPrice = content.getString("Price");
        jhTmGoods.setJhPromoprice(promoPrice);

        // 库存 不一定准
        Long quantity = content.getLong("quantity");
        jhTmGoods.setJhQuantity(quantity);

        // 已知 有颜色分类信息
        JSONArray saleProps = content.getJSONArray("specsList");
        jhTmGoods.setJhSaleProps(saleProps);

        // 销量 没啥用
//        String sellTotalStr = content.getString("sellTotal");  // 例如 "500+"
//        String numberStr = sellTotalStr.replaceAll("\\D+", ""); // 去除非数字字符
//        int sellTotal = Integer.parseInt(numberStr);
//        jhTmGoods.setJhSell(sellTotal);

        String shopId = content.getString("shopId");
        jhTmGoods.setJhShopId(shopId);

        String shopName = content.getString("shopName");
        jhTmGoods.setJhShopName(shopName);

        jhTmGoods.setJhSkus(skus);

        String title = content.getString("goodsName");
        if (title.length() > 30) {
            title = title.substring(0, 30);
        }
        jhTmGoods.setJhTitle(title);

        String video = content.getString("videoUrl");
        jhTmGoods.setJhVideo(video);
        return jhTmGoods;
    }

    private void checkCodeOrThrow(String jsonStr) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(jsonStr);

            if (rootNode.has("code")) {
                JsonNode codeNode = rootNode.get("code");
                JsonNode msgNode = rootNode.get("msg");

                if (!codeNode.isTextual() || !"000000".equals(codeNode.asText())) {
                    throw new RuntimeException("code：" + codeNode.asText() + "，msg：" + msgNode.asText());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("解析 JSON 失败或 code 校验失败", e);
        }
    }
}
